/**
 * 发起 HTTP 网络请求
 * @param {string} url 
 * @param {object} data 
 * @param {GET,POST,PUT,DELETE} method 
 */
function request(url, data = {}, method, head = "application/json") {
	const token = uni.getStorageSync('token') || '';
	// 公有参数与私有参数合并
	// data = {
	// 	...data
	// };
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			data: data,
			sslVerify: false,
			method: method,
			header: {
				'Content-Type': head,
				'Authorization': `Bearer ` + token
			},
			success: (res) => {
				res = res.data;
				//共同请求拦截处理
				if (res.successful == true || res.code == 200) {
					resolve(res);
				} else {
					uni.showToast({
						icon: "none",
						title: res.resultHint,
						duration: 1000
					})
					setTimeout(() => {
						if (res.resultHint == "认证失败，无法访问系统资源") { //token过期
							uni.removeStorageSync('token');
							uni.removeStorageSync('userInfo');
							uni.reLaunch({
								url: '/pages/login/login'
							})
						}
					}, 1000)
					reject(res);
				}
			},
			fail: (err) => {
				uni.showToast({
					icon: "none",
					title: "请求错误"
				})
				console.error(err, url)
				// reject(err)
			},
			complete: () => {

			}
		})
	});
}

module.exports = {
	request,
}
